<template>
  <div>
    <el-row>
      <el-col style="margin-top: 30px; position: relative">
        <el-date-picker
          v-model="datetime"
          type="date"
          placeholder="请选择预约检测时间"
          @change="TimeChange"
        />
        <el-cascader
          v-model="menzhen"
          :options="options2"
          placeholder="请选择预约门诊"
          @change="handleChange"
          clearable
        />
        <el-select
          v-model="Type"
          placeholder="检测状态"
          style="width: 240px; height: 32px; margin-left: 10px"
          @change="GetList()"
          clearable
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-button
          type="primary"
          plain
          style="width: 20%; position: absolute; right: 0"
          class="active-button"
          @click="down_load"
          >导出</el-button
        >
      </el-col>

      <el-col style="margin-top: 10px">
        <el-table
          class="box-table"
          :data="Data"
          :stripe="true"
          :border="true"
          :fit="true"
          v-if="Data != null"
        >
          <el-table-column
            prop="Name"
            label="预约人"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>
          <el-table-column
            prop="Phone"
            label="手机号"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>
          <el-table-column
            prop="Sex"
            label="性别"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>
          <el-table-column
            prop="Age"
            label="年龄"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>
          <el-table-column
            prop="CreateTime"
            label="预约日期"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>
          <el-table-column
            prop="AppointmentTime"
            label="预约检测日期"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>

          <el-table-column
            prop="TimeSlot"
            label="预约检测时段"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>
          <el-table-column
            prop="OutpatientName"
            label="预约门诊(点)"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>

          <el-table-column label="检测状态" align="center" width="auto">
            <template #default="scope">
              <el-button
                link
                style="color: blue"
                type="primary"
                size="small"
                v-if="scope.row.Arrive == '待检测'"
                @click="
                  dialogFormVisible = true;
                  id = scope.row.Id;
                "
                >待检测</el-button
              >
              <el-button
                v-if="scope.row.Arrive == '未检测'"
                link
                type="primary"
                size="small"
                style="color: red"
                >未检测</el-button
              >
              <el-button
                v-if="scope.row.Arrive == '已检测'"
                link
                type="primary"
                size="small"
                style="color: green"
                >已检测</el-button
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="Remark"
            label="未检测原因"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>
        </el-table>
      </el-col>
      <el-col style="margin: 0 auto">
        <el-card>
          <div class="block">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="pageSize"
              :total="Total"
            >
            </el-pagination>
          </div>
        </el-card>
      </el-col>

      <el-dialog
        title="修改检测状态"
        v-model="dialogFormVisible"
        width="30%"
        :before-close="handleClose"
      >
        <el-select
          v-model="arriveStatus"
          placeholder="检测状态"
          size="large"
          style="width: 240px"
        >
          <el-option
            v-for="item in options_2"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-date-picker
          v-if="arriveStatus == '已检测'"
          v-model="arriveTime"
          type="datetime"
          placeholder="选择检测时间"
          style="margin-top: 20px"
          @change="PopChange"
        />
        <el-input
          style="margin-top: 20px"
          v-if="arriveStatus == '未检测'"
          placeholder="请填写未检测原因(必填)"
          v-model="remark"
        ></el-input>
        <div slot="footer" class="dialog-footer" style="margin-top: 10px">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="onsit">确 定</el-button>
        </div>
      </el-dialog>
    </el-row>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, toRaw, onMounted, onBeforeMount } from "vue";
import apiService from "@/services/apiService";
import { conversionUtcDate, base64ToExcelAndDownload } from "@/utils/auth";
import { v4 as uuidv4 } from "uuid";
import { ElMessageBox, ElMessage } from "element-plus";
import { store } from "@/store";

defineOptions({
  // name 作为一种规范最好必须写上并且和路由的name保持一致
  name: "Zixun"
});

//表格数据
const Data = ref<any>([]);
const currentPage = ref(1); // 当前页数
const pageSize = ref(10); // 每页条数
const Total = ref<number>(1); //总条数
const datetime = ref<any>("");
const Type = ref<any>("");
const role = ref<any>("");
const options = [
  {
    value: "待检测",
    label: "待检测"
  },
  {
    value: "已检测",
    label: "已检测"
  },
  {
    value: "未检测",
    label: "未检测"
  }
];
const menzhen = ref("");
const options2 = [
  {
    value: "涪城区",
    label: "涪城区",
    children: [
      {
        value: "绵阳市疾病预防控制中心",
        label: "绵阳市疾病预防控制中心"
      },
      {
        value: "涪城区疾病预防控制中心",
        label: "涪城区疾病预防控制中心"
      },
      {
        value: "绵阳市人民医院",
        label: "绵阳市人民医院"
      },
      {
        value: "涪城区妇幼保健计划生育服务中心",
        label: "涪城区妇幼保健计划生育服务中心"
      }
    ]
  },
  {
    value: "游仙区",
    label: "游仙区",
    children: [
      {
        value: "游仙区疾病预防控制中心",
        label: "游仙区疾病预防控制中心"
      },
      {
        value: "游仙区人民医院",
        label: "游仙区人民医院"
      },
      {
        value: "游仙区妇幼保健院",
        label: "游仙区妇幼保健院"
      }
    ]
  },
  {
    value: "安州区",
    label: "安州区",
    children: [
      {
        value: "安州区疾病预防控制中心",
        label: "安州区疾病预防控制中心"
      }
    ]
  },
  {
    value: "三台县",
    label: "三台县",
    children: [
      {
        value: "三台县疾病预防控制中心",
        label: "三台县疾病预防控制中心"
      }
    ]
  },
  {
    value: "盐亭县",
    label: "盐亭县",
    children: [
      {
        value: "盐亭县疾病预防控制中心",
        label: "盐亭县疾病预防控制中心"
      },
      {
        value: "盐亭县人民医院",
        label: "盐亭县人民医院"
      }
    ]
  },
  {
    value: "梓潼县",
    label: "梓潼县",
    children: [
      {
        value: "梓潼县疾病预防控制中心",
        label: "梓潼县疾病预防控制中心"
      },
      {
        value: "梓潼县人民医院",
        label: "梓潼县人民医院"
      }
    ]
  },
  {
    value: "北川羌族自治县",
    label: "北川羌族自治县",
    children: [
      {
        value: "北川羌族自治县疾病预防控制中心",
        label: "北川羌族自治县疾病预防控制中心"
      }
    ]
  },
  {
    value: "平武县",
    label: "平武县",
    children: [
      {
        value: "平武县疾病预防控制中心",
        label: "平武县疾病预防控制中心"
      }
    ]
  },
  {
    value: "江油市",
    label: "江油市",
    children: [
      {
        value: "江油市疾病预防控制中心",
        label: "江油市疾病预防控制中心"
      },
      {
        value: "江油市传染病医院",
        label: "江油市传染病医院"
      },
      {
        value: "江油市妇幼保健计划生育服务中心",
        label: "江油市妇幼保健计划生育服务中心"
      }
    ]
  }
];
const TimeChange = () => {
  console.log(datetime.value);

  if (datetime.value != null) {
    datetime.value = conversionUtcDate(datetime.value, "local");
    console.log(datetime.value);
    GetList();
  } else {
    datetime.value = "";
    GetList();
  }
};
const handleChange = () => {
  if (menzhen.value != null) {
    GetList();
  } else {
    menzhen.value = "";
    GetList();
  }
};
//获取表单数据
const GetList = () => {
  console.log(store.state.value.userRole.userid);

  const params = {
    msgid: "GetPagedAppointments",
    token: "BC65FD34-931E-6E6D-7979-EFD67A547B56",
    seq: uuidv4(),
    body: {
      adminid: localStorage.getItem("userid"),
      pageNumber: currentPage.value,
      pageSize: pageSize.value,
      arrive: Type.value,
      queryDate: datetime.value,
      outpatientname: menzhen.value[1]
    }
  };

  apiService
    .post("", params)
    .then((res: any) => {
      // 使用 any 类型断言
      console.log(res.data);
      let arr = res.data.body.Data.Appointments;
      for (let i = 0; i < arr.length; i++) {
        // arr[i].AppointmentTime = conversionUtcDate(arr[i].AppointmentTime, "local");
        arr[i].AppointmentTime = arr[i].AppointmentTime.split("T")[0];
        if (arr[i].ArriveTime != null) {
          arr[i].ArriveTime = arr[i].ArriveTime.split("T")[0];
        }
        if (arr[i].CreateTime != null) {
          arr[i].CreateTime = arr[i].CreateTime.split("T")[0];
        }
      }
      Data.value = arr;
      Total.value = res.data.body.Data.TotalRecords;
    })
    .catch(error => {
      console.error("Error fetching data:", error);
    });
};

//详情数据
const msg_info = ref<any>([]);
const info = row => {
  msg_info.value = row.recorddetails;
};

//导出
const down_load = () => {
  const params = {
    msgid: "ExportAppointments",
    token: "BC65FD34-931E-6E6D-7979-EFD67A547B56",
    seq: uuidv4(),
    body: {
      adminid: localStorage.getItem("userid")
    }
  };
  apiService.post("", params).then((res: any) => {
    base64ToExcelAndDownload(res.data.body.base64data, res.data.body.name);
  });
};

const dialogFormVisible = ref(false);

const id = ref<any>("");
const arriveStatus = ref<any>("");
const arriveTime = ref<any>("");
const remark = ref<any>("");
const options_2 = [
  {
    value: "已检测",
    label: "已检测"
  },
  {
    value: "未检测",
    label: "未检测"
  }
];
const PopChange = () => {
  if (arriveTime.value != null) {
    return;
  } else {
    arriveTime.value = "";
  }
};
const onsit = () => {
  if (arriveStatus.value == "") {
    ElMessage({
      type: "error",
      message: "请选择检测状态"
    });
  } else {
    if (arriveStatus.value == "已检测") {
      if (arriveTime.value == "") {
        ElMessage({
          type: "error",
          message: "请选择检测时间"
        });
      } else {
        const params = {
          msgid: "UpdateAppointmentArriveAndTime",
          token: "BC65FD34-931E-6E6D-7979-EFD67A547B56",
          seq: uuidv4(),
          body: {
            id: id.value,
            arriveStatus: "已检测",
            arriveTime: arriveTime.value,
            remark: ""
          }
        };
        apiService.post("", params).then((res: any) => {
          console.log(res);
          if (res.data.code == 200) {
            ElMessage({
              type: "success",
              message: "完成检测"
            });
            dialogFormVisible.value = false;
            GetList();
          }
        });
      }
    } else if (arriveStatus.value == "未检测") {
      if (remark.value == "") {
        ElMessage({
          type: "error",
          message: "请填写未检测原因"
        });
      } else {
        const params = {
          msgid: "UpdateAppointmentArriveAndTime",
          token: "BC65FD34-931E-6E6D-7979-EFD67A547B56",
          seq: uuidv4(),
          body: {
            id: id.value,
            arriveStatus: "未检测",
            arriveTime: "",
            remark: remark.value
          }
        };
        apiService.post("", params).then((res: any) => {
          console.log(res);
          if (res.data.code == 200) {
            ElMessage({
              type: "success",
              message: "状态修改完成"
            });
            dialogFormVisible.value = false;
            GetList();
          }
        });
      }
    }
  }
};

const change = id => {
  ElMessageBox.confirm("确认该申请人已检测？", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      const params = {
        msgid: "UpdateAppointmentArriveAndTime",
        token: "BC65FD34-931E-6E6D-7979-EFD67A547B56",
        seq: uuidv4(),
        body: {
          appointmentId: id
        }
      };
      apiService.post("", params).then((res: any) => {
        console.log(res);
        if (res.data.code == 200) {
          ElMessage({
            type: "success",
            message: "确认成功"
          });
          GetList();
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消"
      });
    });
};
// 监听页码变化
const handleCurrentChange = val => {
  currentPage.value = val;
  GetList();
};

// 监听每页条数变化
const handleSizeChange = val => {
  pageSize.value = val;
};

const handleClose = (done: () => void) => {
  arriveTime.value = "";
  remark.value = "";
  arriveStatus.value = "";
  done();
  // })
  // .catch(() => {
  //   // catch error
  // });
};
onBeforeMount(() => {
  // GetList();
});
onMounted(() => {
  GetList();
  role.value = localStorage.getItem("role");
  console.log(localStorage.getItem("role"));
});
</script>

<style lang="scss" scoped>
.active-button {
  background-color: #409eff; /* 设置按钮激活时的背景颜色 */
  color: white; /* 设置按钮激活时的文字颜色 */
}
</style>
